package com.example.langchain4j.service;

import cn.hutool.json.JSONUtil;
import com.deepoove.poi.XWPFTemplate;
import com.example.langchain4j.common.constant.PromptConstant;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.model.chat.response.ChatResponse;
import dev.langchain4j.model.input.Prompt;
import dev.langchain4j.model.input.PromptTemplate;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class InterrogationGenerationService {

    @Autowired
    @Qualifier("chatLanguageModel")
    private ChatLanguageModel qwenChatModel;

    private static final String GENERATED_DIR = "src/main/resources/generated";

    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 生成询问笔录 - 使用模板填充方式（与立案审批表生成方式一致）
     * @param caseApprovalContent 立案审批表的JSON内容
     * @param sessionId 会话ID
     * @return 包含wordPath, htmlPath, jsonData的结果
     */
    public Map<String, Object> generateInterrogationRecord(String caseApprovalContent, String sessionId) {
        log.info("开始生成询问笔录, sessionId: {}", sessionId);

        try {
            // 解析立案审批表JSON数据
            JsonNode caseData = objectMapper.readTree(caseApprovalContent);

            // 构建提示词，让AI生成询问笔录JSON
            String prompt = buildInterrogationPrompt(caseData);

            // 调用ChatLanguageModel生成询问笔录JSON内容
            log.info("调用ChatLanguageModel生成询问笔录JSON...");
            ChatResponse chatResponse = qwenChatModel.chat(dev.langchain4j.data.message.UserMessage.from(prompt));
            String biluJsonRes = chatResponse.aiMessage().text();
            log.info("原始响应长度: {}", biluJsonRes.length());

            // 清理JSON字符串（移除可能的markdown标记）
            biluJsonRes = cleanJsonString(biluJsonRes);
            log.info("生成的笔录JSON: {}", biluJsonRes);

            // 确保generated目录存在
            Path generatedPath = Paths.get(GENERATED_DIR);
            if (!Files.exists(generatedPath)) {
                Files.createDirectories(generatedPath);
            }

            // 生成文件名
            String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
            String fileName = "询问笔录_" + timestamp + ".docx";
            String filePath = GENERATED_DIR + "/" + fileName;

            // 填充word模板并保存到文件
            Map<String, Object> resultMap = JSONUtil.toBean(biluJsonRes, Map.class);
            Object qs = resultMap.get("questions");
            if (qs instanceof cn.hutool.json.JSONArray jsonArray) {
                resultMap.put("questions", jsonArray.toList(String.class));  // 转为 List<String>
            }

            ClassPathResource resource = new ClassPathResource("询问笔录template.docx");
            InputStream templateInputStream = resource.getInputStream();
            XWPFTemplate template = XWPFTemplate.compile(templateInputStream).render(resultMap);

            // 保存到本地文件
            FileOutputStream fileOut = new FileOutputStream(filePath);
            template.write(fileOut);
            fileOut.close();
            template.close();

            log.info("询问笔录文件已保存: {}", filePath);

            // 构建返回结果（字段名与前端保持一致）
            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("fileName", fileName);
            result.put("filePath", "http://localhost:8018/api/dify/generated/" + fileName);  // 前端需要的文件访问路径
            result.put("jsonData", biluJsonRes);
            result.put("message", "询问笔录生成成功");

            log.info("询问笔录生成完成，返回结果: {}", result);
            return result;

        } catch (Exception e) {
            log.error("生成询问笔录失败", e);
            throw new RuntimeException("生成询问笔录失败: " + e.getMessage(), e);
        }
    }

    /**
     * 构建询问笔录生成提示词 - 使用PromptConstant中的标准模板
     */
    private String buildInterrogationPrompt(JsonNode caseData) {
        // 使用PromptTemplate和PromptConstant.generalBiluJson
        PromptTemplate promptTemplate = PromptTemplate.from(PromptConstant.generalBiluJson);

        HashMap<String, Object> variables = new HashMap<>();
        variables.put("caseApprovalJson", caseData.toPrettyString());

        Prompt prompt = promptTemplate.apply(variables);
        return prompt.text();
    }

    /**
     * 清理JSON字符串，移除markdown代码块标记和额外说明
     * 特别处理推理模型（如qwq）的思考过程输出
     */
    private String cleanJsonString(String jsonString) {
        if (jsonString == null || jsonString.trim().isEmpty()) {
            return jsonString;
        }

        String cleaned = jsonString.trim();

        // 移除开头的markdown标记
        if (cleaned.startsWith("```json")) {
            cleaned = cleaned.substring(7);
        } else if (cleaned.startsWith("```")) {
            cleaned = cleaned.substring(3);
        }

        // 移除结尾的markdown标记
        if (cleaned.endsWith("```")) {
            cleaned = cleaned.substring(0, cleaned.length() - 3);
        }

        cleaned = cleaned.trim();

        // 特殊处理：如果内容包含思考过程（常见于推理模型），尝试提取JSON部分
        // 查找最后一个完整的JSON对象（从最后一个 } 往前找到对应的 {）
        int lastBrace = cleaned.lastIndexOf('}');
        if (lastBrace != -1) {
            // 从lastBrace往前找匹配的 {
            int braceCount = 1;
            int firstBrace = lastBrace - 1;
            while (firstBrace >= 0 && braceCount > 0) {
                if (cleaned.charAt(firstBrace) == '}') {
                    braceCount++;
                } else if (cleaned.charAt(firstBrace) == '{') {
                    braceCount--;
                }
                firstBrace--;
            }
            firstBrace++; // 调整到 { 的位置

            if (firstBrace >= 0 && braceCount == 0) {
                // 找到了完整的JSON对象
                String potentialJson = cleaned.substring(firstBrace, lastBrace + 1);
                // 验证是否像JSON（简单检查：包含引号和冒号）
                if (potentialJson.contains("\"") && potentialJson.contains(":")) {
                    cleaned = potentialJson;
                    log.info("从推理模型输出中提取到JSON，长度: {}", cleaned.length());
                }
            }
        }

        // 如果上面没有找到，使用原来的逻辑：查找第一个 { 和最后一个 }
        if (!cleaned.startsWith("{")) {
            int firstBrace = cleaned.indexOf('{');
            int lastBraceSimple = cleaned.lastIndexOf('}');

            if (firstBrace != -1 && lastBraceSimple != -1 && firstBrace < lastBraceSimple) {
                // 提取 {} 之间的内容
                cleaned = cleaned.substring(firstBrace, lastBraceSimple + 1);
            }
        }

        return cleaned.trim();
    }
}
